<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\SpecificationTemplate;
use App\Models\Category;
use App\Traits\LogsActivity;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class AdminSpecificationTemplateController extends Controller
{
    use LogsActivity;
    /**
     * 显示规格模板列表
     */
    public function index(): Response
    {
        $templates = SpecificationTemplate::with(['category'])
            ->orderBy('sort_order', 'desc')
            ->orderBy('created_at', 'desc')
            ->get()
            ->map(function ($template) {
                return [
                    'id' => $template->id,
                    'name' => $template->name,
                    'slug' => $template->slug,
                    'description' => $template->description,
                    'category' => $template->category ? [
                        'id' => $template->category->id,
                        'name' => $template->category->name,
                    ] : null,
                    'is_active' => $template->is_active,
                    'is_default' => $template->is_default,
                    'sort_order' => $template->sort_order,
                    'attributes_count' => count($template->attributes_config ?? []),
                    'created_at' => $template->created_at->format('Y-m-d H:i:s'),
                ];
            });

        return Inertia::render('Admin/SpecificationTemplates/Index', [
            'templates' => $templates,
        ]);
    }

    /**
     * 显示创建规格模板表单
     */
    public function create(): Response
    {
        $categories = Category::where('is_active', true)
            ->orderBy('sort_order', 'desc')
            ->orderBy('name')
            ->get(['id', 'name']);

        return Inertia::render('Admin/SpecificationTemplates/Create', [
            'categories' => $categories,
        ]);
    }

    /**
     * 存储新的规格模板
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'slug' => 'required|string|max:255|unique:specification_templates,slug',
            'description' => 'nullable|string',
            'category_id' => 'nullable|exists:categories,id',
            'attributes_config' => 'required|array',
            'is_active' => 'boolean',
            'is_default' => 'boolean',
            'sort_order' => 'integer|min:0',
        ]);

        $template = SpecificationTemplate::create([
            'name' => $request->name,
            'slug' => $request->slug,
            'description' => $request->description,
            'category_id' => $request->category_id,
            'attributes_config' => $request->attributes_config,
            'display_config' => $request->display_config ?? [],
            'is_active' => $request->boolean('is_active', true),
            'is_default' => $request->boolean('is_default', false),
            'sort_order' => $request->sort_order ?? 0,
        ]);

        // 记录日志
        $this->logCreate(
            module: 'specification-templates',
            itemName: $template->name,
            model: $template
        );

        return redirect()->route('specification-templates.index')
            ->with('success', '规格模板创建成功！');
    }

    /**
     * 显示编辑规格模板表单
     */
    public function edit(SpecificationTemplate $specificationTemplate): Response
    {
        $categories = Category::where('is_active', true)
            ->orderBy('sort_order', 'desc')
            ->orderBy('name')
            ->get(['id', 'name']);

        return Inertia::render('Admin/SpecificationTemplates/Edit', [
            'template' => [
                'id' => $specificationTemplate->id,
                'name' => $specificationTemplate->name,
                'slug' => $specificationTemplate->slug,
                'description' => $specificationTemplate->description,
                'category_id' => $specificationTemplate->category_id,
                'attributes_config' => $specificationTemplate->attributes_config,
                'display_config' => $specificationTemplate->display_config,
                'is_active' => $specificationTemplate->is_active,
                'is_default' => $specificationTemplate->is_default,
                'sort_order' => $specificationTemplate->sort_order,
            ],
            'categories' => $categories,
        ]);
    }

    /**
     * 更新规格模板
     */
    public function update(Request $request, SpecificationTemplate $specificationTemplate)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'category_id' => 'nullable|exists:categories,id',
            'attributes_config' => 'required|array',
            'is_active' => 'boolean',
            'is_default' => 'boolean',
            'sort_order' => 'integer|min:0',
        ]);

        $specificationTemplate->update([
            'name' => $request->name,
            'description' => $request->description,
            'category_id' => $request->category_id,
            'attributes_config' => $request->attributes_config,
            'display_config' => $request->display_config ?? [],
            'is_active' => $request->boolean('is_active', true),
            'is_default' => $request->boolean('is_default', false),
            'sort_order' => $request->sort_order ?? 0,
        ]);

        // 记录日志
        $this->logUpdate(
            module: 'specification-templates',
            itemName: $specificationTemplate->name,
            model: $specificationTemplate
        );

        return redirect()->route('specification-templates.index')
            ->with('success', '规格模板更新成功！');
    }

    /**
     * 删除规格模板
     */
    public function destroy(SpecificationTemplate $specificationTemplate)
    {
        $templateName = $specificationTemplate->name;
        $specificationTemplate->delete();

        // 记录日志
        $this->logDelete(
            module: 'specification-templates',
            itemName: $templateName,
            model: null
        );

        return redirect()->route('specification-templates.index')
            ->with('success', '规格模板删除成功！');
    }

    /**
     * 切换模板状态
     */
    public function toggleStatus(SpecificationTemplate $specificationTemplate)
    {
        $specificationTemplate->update([
            'is_active' => !$specificationTemplate->is_active,
        ]);

        // 记录日志
        $this->logToggleStatus(
            module: 'specification-templates',
            itemName: $specificationTemplate->name,
            status: $specificationTemplate->is_active ? '启用' : '禁用',
            model: $specificationTemplate
        );

        return redirect()->route('specification-templates.index')
            ->with('success', '模板状态更新成功！');
    }

    /**
     * 获取分类的规格模板
     */
    public function getTemplatesForCategory(Category $category)
    {
        $templates = SpecificationTemplate::forCategory($category->id)
            ->active()
            ->ordered()
            ->get()
            ->map(function ($template) {
                return [
                    'id' => $template->id,
                    'name' => $template->name,
                    'slug' => $template->slug,
                    'attributes_config' => $template->attributes_config,
                ];
            });

        return response()->json($templates);
    }
}
